import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lenovo
 * Date: 2022-12-18
 * Time: 21:52
 */@WebServlet("/blog_delete")
public class BlogDeleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.先判定用户的登入状态---拿到当前用户的登入信息->拿到userId与blog对象里userId进行比较来判能否删除这篇博客
        HttpSession session = req.getSession(false);
        if(session == null){
            resp.setStatus(403);
            resp.setContentType("text/html ; charset=utf8");
            resp.getWriter().write("未登入!!!无法删除文章");
            return;
        }
        User user = (User) session.getAttribute("user");
        if(user == null){
            resp.setStatus(403);
            resp.setContentType("text/html ; charset=utf8");
            resp.getWriter().write("未登入!!!无法删除文章");
            return;
        }
        //2.获取到blogId
        String blogId = req.getParameter("blogId");
        if(blogId == null){
            resp.setStatus(403);
            resp.setContentType("text/html ; charset=utf8");
            resp.getWriter().write("blogId为空");
            return;
        }
        //3.查询出blogId对应的blog对象
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.selectOne(Integer.parseInt(blogId));
        if(blog == null){
            resp.setStatus(403);
            resp.setContentType("text/html ; charset=utf8");
            resp.getWriter().write("不存在博客blogId="+blogId);
            return;
        }
        //4.判定登录用户是否为文章作者
        if(blog.getUserId() != user.getUserId()){
            //登入的用户不是文章的作者,不允许删除
            resp.setStatus(403);
            resp.setContentType("text/html ; charset=utf8");
            resp.getWriter().write("您不是文章作者,没有删除权限!!!");
            return;

        }
        //5.真正执行删除操作
        blogDao.delete(Integer.parseInt(blogId));
        //6.302重定向到博客列表页
        resp.sendRedirect("blog_list.html");


    }
}
